package com.knowif.backend.controller;

import com.knowif.backend.service.TUserService;
import com.knowif.backend.util.AliyunMessageUtil;
import com.knowif.backend.util.YZMUtil;
import com.knowif.pojo.TUser;
import com.knowif.system.model.RestBean;
import com.knowif.util.commonUtil.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author xingyao
 * @Description: 用户控制层
 */
@RestController
@RequestMapping("/wechat/user")
public class TUserController {
	
	@Autowired
	private TUserService tUserService;
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	
	
	/**
	 * @author: xingyao 
	 * @Description:  用于个人中心查找
	 * @param userId
	 * @return
	 */
	@PostMapping("/selectUserInfo")
	public RestBean<?> selectUserInfo(Integer userId){
		if(userId == null){
			return RestBean.buildError("请输入要查找的导师id");
		}
		return tUserService.selectTUserInfo(userId);
	}

	/**
	 * 发送短信验证码
	 * @param phone
	 */
	@GetMapping("/sendVerificationCode")
	public RestBean sendVerificationCode(String phone){
		//生成6位数验证码
		String yzm = YZMUtil.randomCode();
		//放入redis3分钟
		stringRedisTemplate.opsForValue().set(phone, yzm, 3, TimeUnit.MINUTES);
		//发送验证码
		AliyunMessageUtil.sendVerificationCode(yzm,phone);
		return RestBean.buildSuccess("发送成功");
	}

	/**
	 * 验证验证码，成功则更新用户电话号码及微信
	 * @param tUser
	 * @return
	 */
	@PostMapping("/updatePhoneAndWechat")
	public RestBean<?> updatePhoneAndWechat(@RequestBody TUser tUser){
		String code = tUser.getCode();
		String phoneNum = tUser.getPhoneNum();
		if(StringUtil.isEmpty(phoneNum)){
			return RestBean.buildError("手机号为空");
		}
		if(StringUtil.isEmpty(code)){
			return RestBean.buildError("验证码为空");
		}
		String redisCode = stringRedisTemplate.opsForValue().get(phoneNum);
		if(!code.equals(redisCode)){
			return RestBean.buildError("验证码不正确");
		}else{
			stringRedisTemplate.delete(phoneNum);
			return tUserService.updateUserInfo(tUser);
		}
	}

}










